package ui.forms;

import ui.*;
import base.*;
import db.*;
import stub.*;
import com.sun.lwuit.*;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.*;
import java.util.Date;
import javax.microedition.midlet.MIDlet;
import utils.Config;

/**
 * Register a new user and update the local db
 * @author Meera, Shayan
 */
class SignUpForm extends Form implements ActionListener {

    private InputField txtUserName;
    private InputField txtPassword;
    private DateField txtDateOfBirth;
    private NumericField txtWeight;
    private NumericField txtHeight;
    private SexField lstSex;
    private Button btnRegister;
    private Progress progress;
    private Command cmdBack;
    private MIDlet parentMidlet;

    SignUpForm(final Form parent, final MIDlet parentMidlet) {
        this.parentMidlet = parentMidlet;
        this.setTitle("Sign up");

        this.setLayout(new BorderLayout());

        btnRegister = new Button("Register");
        btnRegister.addActionListener(this);

        Container fields = new Container();
        fields.setLayout(new BoxLayout(BoxLayout.Y_AXIS));

        txtUserName = new InputField("Username:", true);
        fields.addComponent(txtUserName);

        txtPassword = new InputField("password:", true);
        txtPassword.getTextField().setConstraint(TextField.PASSWORD);
        fields.addComponent(txtPassword);

        txtDateOfBirth = new DateField("DOB:", new Date());
        fields.addComponent(txtDateOfBirth);

        txtHeight = new NumericField("Height(cm):");
        fields.addComponent(txtHeight);

        txtWeight = new NumericField("Weight(kg):");
        fields.addComponent(txtWeight);

        lstSex = new SexField();
        fields.addComponent(lstSex);

        progress = new Progress();
        progress.setVisible(false);
        fields.addComponent(progress);

        Container buttons = new Container(new FlowLayout(Component.CENTER));
        buttons.addComponent(btnRegister);
        fields.addComponent(buttons);

        this.addComponent(BorderLayout.CENTER, fields);

        cmdBack = new Command("Back") {

            public void actionPerformed(ActionEvent evt) {
                parent.showBack();
            }
        };
        this.addCommand(cmdBack);
        this.setBackCommand(cmdBack);

        this.addCommand(new Command("Change Server") {

            public void actionPerformed(ActionEvent evt) {
                ChangeServerForm form = new ChangeServerForm(SignUpForm.this);
                form.show();
            }
        });

        this.addCommandListener(this);
        txtUserName.setFocus(true);
    }

    public void actionPerformed(ActionEvent evt) {
        try {
            if (evt.getSource() == btnRegister) {

                if (validate()) {
                    final User user = new User();
                    user.setName(txtUserName.getText());
                    user.setPassword(txtPassword.getText());
                    user.setDateOfBirth((Date) txtDateOfBirth.getDate());
                    user.setHeight(Float.parseFloat(txtHeight.getText()));
                    user.setWeight(Float.parseFloat(txtWeight.getText()));
                    user.setSex(lstSex.getSelectedSex());
                    try {
                        user.validate();
                    } catch (ValidationException ex) {
                        Dialog.show("Error", ex.getMessage(), "OK", "");
                    }

                    new BackgroundTask() {

                        public void performTask() {
                            try {
                                progress.setVisible(true);
                                progress.setProgress(10);
                                UserServicesSoap_Stub userServices = new UserServicesSoap_Stub();
                                if (userServices.register(user)) {
                                    progress.setProgress(50);
                                    UserManager.persist(user);

                                    progress.setProgress(100);
                                    progress.setVisible(false);
                                    Dialog.show("Registration successful", "Your username is \n " + user.getName(), "OK", "");
                                    Context.currentUser = user;
                                    Config.setRememberedUserId(Context.currentUser.getId());
                                    //show main menu.
                                    MainMenu form = new MainMenu(parentMidlet);
                                    form.show();
                                } else {
                                    progress.setProgress(100);
                                    progress.setVisible(false);
                                    Dialog.show("Error", "Username already Exist.", "OK", "");
                                }
                            } catch (Exception ex) {
                                progress.setProgress(100);
                                progress.setVisible(false);
                                Dialog.show("Error", ex.getMessage(), "OK", "");
                            }
                        }
                    }.start();

                }
            }
        } catch (Exception err) {
            Dialog.show("Error", err.getMessage(), "OK", "");
        }
    }

    private boolean validate() {
        if (txtUserName.getText().equals("")) {
            Dialog.show("Error", "Please provide a value for Username", "OK", "");
            return false;
        }

        if (txtPassword.getText().equals("")) {
            Dialog.show("Error", "Please provide a value for Password", "OK", "");
            return false;
        }

        if (txtHeight.getText().equals("")) {
            Dialog.show("Error", "Please provide a value for Height", "OK", "");
            return false;
        }

        if (txtWeight.getText().equals("")) {
            Dialog.show("Error", "Please provide a value for Weight", "OK", "");
            return false;
        }

        if (!txtDateOfBirth.isValid()) {
            Dialog.show("Error", "Invalid Date of Birth", "OK", "");
            return false;
        }
        try {
            if (UserManager.getByName(txtUserName.getText()) != null) {
                Dialog.show("Error", "Username already exists", "OK", "");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            Dialog.show("Error", ex.toString(), "OK", "");
        }

        return true;
    }
}
